import { useContext, useEffect, useState } from "react";
import MsgContext from "./createContext";

function Son(props: {
  node: React.ReactNode;
  children: React.ReactNode;
  onGetMsg: (msg: string) => void;
}) {
  const msg = useContext(MsgContext);

  useEffect(() => {
    const timer = setInterval(() => {
      console.log("定时器");
    }, 1000);

    return () => {
      // 清除副作用
      clearInterval(timer);
    };
  }, []);

  return (
    <div>
      {props.node}
      {props.children}
      <span>{msg}</span>
      <button onClick={() => props.onGetMsg("123")}>获取消息</button>
    </div>
  );
}

export default function Father() {
  const [show, setShow] = useState(true);

  function getMsg(msg: string) {
    console.log(msg);
  }

  return (
    <div>
      {show && (
        <Son node={<span>123</span>} onGetMsg={getMsg}>
          <span>456</span>
        </Son>
      )}
      <button onClick={() => setShow(false)}>卸载Son组件</button>
    </div>
  );
}
